<template>
  <div class="expressManagementContainer">
    <el-card>
      <el-row>
        <el-col :span="6">
          <!-- 搜索 -->
          <el-input
            placeholder="请输入内容"
            v-model="query"
            clearable
            @clear="searchClear"
            @change="searchClick"
          >
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="el-icon-search" @click="searchClick"
            >搜索</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button type="" icon="el-icon-plus" @click="addDialog"
            >添加</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button type="danger" icon="el-icon-delete" @click="batchDelete"
            >删除</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-row :gutter="10">
        <!-- 表格 -->
        <el-table
          :data="depositoryExpressInformation"
          style="width: 100%"
          ref="table"
          v-loading="loading"
        >
          <!-- 多选 -->
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="informationNumber" label="运单号" width="200">
          </el-table-column>
          <el-table-column prop="userId" label="学/工号"> </el-table-column>
          <el-table-column prop="informationName" label="收件人姓名">
          </el-table-column>
          <el-table-column prop="informationMobile" label="收件人手机号">
          </el-table-column>
          <el-table-column
            prop="informationCreateTime"
            label="入库时间"
          ></el-table-column>
          <el-table-column prop="informationSignTime" label="签收时间">
            <template slot-scope="scope">
              <el-tag type="info" v-if="scope.row.informationSignTime == null"
                >未签收</el-tag
              >
              <el-tag type="success" v-else>{{
                scope.row.informationSignTime
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="locationName" label="所属仓位">
          </el-table-column>
          <!-- 操作区 -->
          <el-table-column label="操作">
            <!-- 插槽 slot-scope="scope"-->
            <template slot-scope="scope">
              <el-button
                type=""
                size="small"
                @click="editDialog(scope)"
                v-if="scope.row.informationSignTime == null"
                >修改信息</el-button
              >
              <el-button
                type="success"
                size="small"
                @click="editSignedClick"
                v-else-if="scope.row.informationSignTime != null"
                >快递签收</el-button
              >
              <el-button
                type="danger"
                size="small"
                @click="deleteConfirm(scope)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <!-- 分页 -->
      <!-- 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
       -->
      <el-row :gutter="10">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[8, 16, 24, 32]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalNumber"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @prev-click="handlePrevClick"
          @next-click="handleNextClick"
        >
        </el-pagination>
      </el-row>
    </el-card>
    <!-- 对话框组件 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <!-- Form表单区域 -->
      <el-form ref="form" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="学/工号" prop="userId">
          <el-input v-model="form.userId"></el-input>
        </el-form-item>
        <el-form-item label="运单号" prop="informationNumber">
          <el-input v-model="form.informationNumber"></el-input>
        </el-form-item>
        <el-form-item label="入库时间" prop="informationCreateTime">
          <el-date-picker
            v-model="form.informationCreateTime"
            type="datetime"
            placeholder="选择日期时间"
            class="time"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="签收情况" v-if="dialogTitle == '快递入库信息编辑'">
          <el-switch
            v-model="isSigned"
            @change="switchChange"
            inactive-text="是否签收？"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="签收时间" v-if="dialogTitle == '快递入库信息编辑'">
          <el-date-picker
            v-model="form.informationSignTime"
            type="datetime"
            placeholder="选择日期时间"
            class="time"
            value-format="yyyy-MM-dd HH:mm:ss"
            :disabled="showDatePicker"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="仓位" prop="locationName">
          <el-select
            v-model="form.locationId"
            placeholder="请选择快递所在仓位"
            :disabled="selectDisable"
            filterable 
          >
            <el-option
              v-for="item in locationOptions"
              :key="item.locationId"
              :label="item.locationName"
              :value="item.locationId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "expressManagement",
  data() {
    return {
      loading: false,
      selectDisable: false,
      // 是否展示时间选择
      showDatePicker: false,
      // 是否签收
      isSigned: true,
      // 点击是编辑还是新增标志位
      addOrUpdate: "",
      // 搜索框数据
      query: "",
      // 一页显示个数
      pageSize: 8,
      // 当前页数据
      currentPage: 1,
      // 全部页数据
      totalNumber: 1,
      // 入库快递信息
      depositoryExpressInformation: [],
      // 对话框
      dialogTitle: "",
      dialogVisible: false,
      // 对话框表单区域
      form: {
        userId: "",
        informationId: "",
        informationNumber: "",
        informationCreateTime: "",
        informationSignTime: "",
        locationId: "",
        locationName: "",
        informationName: "",
      },
      // 仓位查询（查询空余仓位）
      locationOptions: [],
      // 新增、修改表单校验
      rules: {
        userId: [
          { required: true, message: "不能为空", trigger: "blur" },
          { pattern: /^\d+$/, message: "只能是数字", trigger: "blur" },
        ],
        informationName: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        informationMobile: [
          { required: true, message: "不能为空", trigger: "blur" },
          {
            pattern: /^(?:(?:\+|00)86)?1\d{10}$/,
            message: "必须为手机号格式",
            trigger: "blur",
          },
        ],
        informationNumber: [
          { required: true, message: "不能为空", trigger: "blur" },
          {
            pattern: /^[A-Za-z0-9]+$/,
            message: "只能是数字和字母",
            trigger: "blur",
          },
        ],
        locationName: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        informationCreateTime: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        informationSignTime: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getExpressData();
  },
  methods: {
    // 已签收点击提示消息
    editSignedClick(){
      this.$message.warning("当前入库信息已签收，不可修改！");
    },
    // 单选框是否签收
    switchChange(e) {
      // 选择了签收
      if (e == true) {
        // 打开时间选择框
        this.showDatePicker = false;
        // 关闭仓位选择
        this.selectDisable = true;
      } else {
        // 选择了没有签收
        this.selectDisable = false;
        this.showDatePicker = true;
        this.form.informationSignTime = "";
      }
    },
    // 赋值方法
    renderTableData(res) {
      this.depositoryExpressInformation = []; // 清空数组
      // 赋值
      for (let i = 0; i < res.data.size; i++) {
        var expressInfoItem = {};
        expressInfoItem.informationId = res.data.list[i].informationId;
        expressInfoItem.informationName = res.data.list[i].informationName;
        expressInfoItem.informationMobile = res.data.list[i].informationMobile;
        expressInfoItem.informationNumber = res.data.list[i].informationNumber;
        expressInfoItem.informationCreateTime =
          res.data.list[i].informationCreateTime;
        expressInfoItem.informationSignTime =
          res.data.list[i].informationSignTime;
        expressInfoItem.locationId = res.data.list[i].locationId;
        expressInfoItem.locationName = res.data.list[i].locationName;
        expressInfoItem.userId = res.data.list[i].userId;
        this.depositoryExpressInformation.push(expressInfoItem);
      }
      // 设置页码
      this.currentPage = res.data.pageNum;
      this.totalNumber = res.data.total;
      this.pageSize = res.data.pageSize;
    },
    // axios初始请求列表数据
    async getExpressData() {
      this.loading = true;
      this.query = "";
      this.pageSize = 8;
      this.currentPage = 1;
      const { data: res } = await axios({
        method: "GET",
        // REST 传递当前页和一页显示条数
        url: `/api/depository/getExpressData/${this.currentPage}/${this.pageSize}`,
        params: {
          query: this.query,
        },
      });
      // 请求成功
      if (res.code == 200) {
        this.renderTableData(res);
      } else {
        this.$message.error("服务器错误，请稍后重试!");
      }
      this.loading = false;
    },
    // 搜索按钮点击
    async searchClick() {
      this.loading = true;
      this.currentPage = 1;
      const { data: res } = await axios({
        method: "GET",
        url: `/api/depository/getExpressData/${this.currentPage}/${this.pageSize}`,
        params: {
          query: this.query,
        },
      });
      if (res.code == 200) {
        this.$message.success("已检索到 " + res.data.list.length + " 条记录");
        this.renderTableData(res);
      } else {
        this.$message.error("服务器错误，请稍后重试!");
      }
      this.loading = false;
    },
    // 处理展示条数项改变
    async handleSizeChange(e) {
      this.loading = true;
      const { data: res } = await axios({
        method: "GET",
        url: `/api/depository/getExpressData/${this.currentPage}/${e}`,
        params: {
          query: this.query,
        },
      });
      if (res.code == 200) {
        this.renderTableData(res);
      } else {
        this.$message.error("服务器错误请稍后重试！");
      }
      this.loading = false;
    },
    // 处理页码数改变
    async handleCurrentChange(e) {
      this.loading = true;
      const { data: res } = await axios({
        method: "GET",
        url: `/api/depository/getExpressData/${e}/${this.pageSize}`,
        params: {
          query: this.query,
        },
      });
      if (res.code == 200) {
        this.renderTableData(res);
      } else {
        this.$message.error("服务器错误请稍后重试！");
      }
      this.loading = false;
    },
    // 搜索框被清空
    searchClear() {
      console.log("清空");
      this.getExpressData();
    },
    // 点击前进
    async handlePrevClick(e) {
      this.loading = true;
      const { data: res } = await axios({
        method: "GET",
        url: `/api/depository/getExpressData/${e}/${this.pageSize}`,
        params: {
          query: this.query,
        },
      });
      if (res.code == 200) {
        this.renderTableData(res);
      } else {
        this.$message.error("服务器错误请稍后重试！");
      }
      this.loading = false;
    },
    // 点击后退
    async handleNextClick(e) {
      this.loading = true;
      const { data: res } = await axios({
        method: "GET",
        url: `/api/depository/getExpressData/${e}/${this.pageSize}`,
        params: {
          query: this.query,
        },
      });
      if (res.code == 200) {
        this.renderTableData(res);
      } else {
        this.$message.error("服务器错误请稍后重试！");
      }
      this.loading = false;
    },
    // 获取对话框的下拉菜单数据
    async getOption() {
      this.locationOptions = [];
      const { data: res } = await axios({
        method: "GET",
        url: "/api/depository/getOption",
      });
      // 赋值到数据模型
      console.log(res);
      for (let i = 0; i < res.data.length; i++) {
        var item = {};
        item.locationId = res.data[i].locationId;
        item.locationName = res.data[i].locationName;
        item.locationStorage = res.data[i].locationStorage;
        this.locationOptions.push(item);
      }
    },
    // 对话框提交数据
    async confirmClick() {
      if (this.addOrUpdate == "update") {
        console.log("点击了确定更新数据");
        if (this.form.informationSignTime == null && this.isSigned == true) {
          this.$message.warning("请填写您的签收时间");
          return;
        }
        // 点击确定是更新标志位
        console.log(this.form);
        const { data: res } = await axios({
          method: "PUT",
          url: "/api/depository/update",
          data: this.form,
        });
        // 处理res
        if (res.code == 403) {
          this.$message.warning("请确认学/工号是否存在!");
        } else if (res.code == 200) {
          this.dialogVisible = false;
          this.$message.success("修改数据成功");
          this.getExpressData();
        } else {
          this.$message.info("服务器发生错误，请稍后重试！");
        }
      } else if (this.addOrUpdate == "add") {
        // 执行新增操作
        console.log("新增");
        console.log(this.form);
        const { data: res } = await axios({
          method: "POST",
          url: "/api/depository/add",
          data: this.form,
        });
        if (res.code == 200) {
          this.$message.success("新增记录成功");
          this.dialogVisible = false;
          this.getExpressData();
        } else if (res.code == 403) {
          this.$message.error("请确认学/公号是否存在！");
        } else {
          this.$message.error("服务器发生错误，请稍后重试！");
        }
      }
    },
    // 对话框编辑
    async editDialog(scope) {
      // 设置标志位
      this.addOrUpdate = "update";
      // 获取下拉框菜单数据
      this.getOption();
      // 发送axios填充信息
      const { data: res } = await axios({
        method: "GET",
        url: "/api/depository/getExpressDescriptionData",
        params: {
          informationId: scope.row.informationId,
          locationId: scope.row.locationId,
        },
      });
      if (res.code == 200) {
        // 回显数据
        this.form.userId = res.data.userId;
        this.form.informationId = res.data.informationId;
        this.form.informationNumber = res.data.informationNumber;
        this.form.informationCreateTime = res.data.informationCreateTime;
        this.form.informationSignTime = res.data.informationSignTime;
        this.form.locationId = res.data.locationId;
        this.form.locationName = res.data.locationName;
        // 当前仓位放入选项中
        var currentItem = {};
        currentItem.locationId = this.form.locationId;
        currentItem.locationName = this.form.locationName;
        this.locationOptions.push(currentItem);
        this.dialogTitle = "快递入库信息编辑";
        this.dialogVisible = true;
        // 设置单选按钮
        if (this.form.informationSignTime) {
          this.isSigned = true;
        } else {
          this.isSigned = false;
          this.showDatePicker = true;
        }
      } else {
        this.$message.error("服务器请求错误，数据回显失败！");
      }
    },
    addDialog() {
      this.locationOptions = [];
      this.getOption(); // 重新请求
      this.addOrUpdate = "add";
      this.form = {};
      this.dialogTitle = "快递入库信息新增";
      this.dialogVisible = true;
    },
    // 删除确认框
    deleteConfirm(scope) {
      this.$confirm("此操作将永久删除该快递入库信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 发请求删除数据
          const { data: res } = await axios({
            method: "DELETE",
            url: "/api/depository/removeExpressData",
            params: {
              informationId: scope.row.informationId,
              locationId: scope.row.locationId,
            },
          });
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getExpressData();
          } else {
            this.$message.error("服务器错误，请稍后重试！");
            this.getExpressData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 批量删除
    batchDelete() {
      this.$confirm("此操作将永久批量删除该快递入库信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const deleteData = this.$refs.table.selection;
          if (deleteData.length == 0) {
            this.$message.info("请选择你要批量删除的数据");
            return;
          }
          // 发送请求批量删除
          const { data: res } = await axios({
            method: "DELETE",
            url: "/api/depository/batchDelete",
            data: deleteData,
          });
          if (res.code == 200) {
            this.$message.success("批量删除成功");
            this.getExpressData();
          } else {
            this.$message.error("删除失败，请稍后重试！");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style>
.expressManagementContainer {
  height: 100%;
  padding: 50px;
}
.expressManagementContainer .el-card {
  margin-top: 0px;
  margin-right: 0px;
}
.el-input.is-active .el-input__inner,
.el-input__inner:focus {
  border-color: #ff84b4 !important;
}
/* 处理表格间距 */
.expressManagementContainer .el-card .el-row:nth-child(2) {
  margin-top: 30px;
}
/* 处理分页间距 */
.expressManagementContainer .el-card .el-row:nth-child(3) {
  margin-top: 30px;
}
/* 处理按钮位置 */
.expressManagementContainer .el-col-2 {
  width: 6.5%;
}
/* 处理时间框大小 */
.expressManagementContainer .time .el-input__inner {
  border-radius: 5px;
  height: 40px !important;
}
/* 处理时间框长度 */
.expressManagementContainer .el-date-editor.el-input,
.expressManagementContainer .el-date-editor.el-input__inner {
  width: 451px !important;
}
</style>